import React from 'react';
import Switch from 'antd/switch';
import Slider from 'antd/slider';
import Radio from 'antd/radio';
const RadioGroup = Radio.Group;
import InputNumber from 'antd/input-number';
import Button from 'antd/button';
import Icon from 'antd/icon';
import Row from 'antd/row';
import Col from 'antd/col';
import Upload from 'antd/upload';
import Modal from 'antd/modal';
const { confirm } = Modal;
import Input from 'antd/input';

import FileLoader from 'ic-file-loader';

import _ from 'lodash';
import './_style/map.less';
import zutil from '../utils/zip';
import { loadData, getData, saveToFile } from '../utils/db';

import saveAs from 'save-as'

export default class Map extends React.Component {

  constructor(props) {
    super(props);
    this.on_change_handler = this.on_change_handler.bind(this);
    this.on_selected_tbl_handler = this.on_selected_tbl_handler.bind(this);
    this.on_unselect = this.on_unselect.bind(this);
    this.on_dodelete = this.on_dodelete.bind(this);
    this.on_click_save = this.on_click_save.bind(this);
    this.on_file_load = this.on_file_load.bind(this);
    this.on_click_add = this.on_click_add.bind(this);

    this.state = {
      selected: undefined,
      tools: {
        zoom: {label: 'Zoom', value: 10,marginLeft:'20px'},
        grid: {label: 'Grid', value: false}
      },
      tables: getData()
    };
  }

  on_change_handler(cpath) {
    return function (evt) {
      var val = evt.target === undefined
        ? evt
        : ( evt.target.type === 'checkbox' ? evt.target.checked : evt.target.value);
      _.set(this.state, cpath, val);
      this.setState({});
    }.bind(this);
  }

  on_click_add(evt) {
    const { tables } = this.state;
    tables.push({
      x: 0,
      y: 2,
      direction: 'n',
      text: '',
      assigned: ''
    });
    this.setState({
      selected: tables.length - 1
    });
  }

  on_selected_tbl_handler(id) {
    return function (evt) {
      this.setState({selected: id});
    }.bind(this);
  }

  on_unselect(evt) {
    this.setState({
      selected: undefined
    });
  }

  on_dodelete(evt) {
    const { tables, selected } = this.state;
    tables.splice(selected, 1);
    this.setState({
      selected: undefined
    });
  }

  on_click_save(evt) {
    const { tables } = this.state;
    //
    (function () {
      var input_fn = '';
      var on_change = function (in_val) {
        input_fn = in_val.target.value;
      };
      confirm({
        title: '请输入文件名:',
        content: <div>
          <Input onChange={on_change}/>
        </div>,
        onOk() {
          var zipfn = (input_fn || 'unknow') + '.map.zip';
          var jsonfn = 'tables.json';
          var blobContent = new Blob([JSON.stringify(tables, null, 2)], {
            type: "text/plain"
          });
          zutil.zipBlob(jsonfn, blobContent, function (zippedBlob) {
            saveAs(zippedBlob, zipfn);
          });
        },
        onCancel() {
        },
      });
      //
    })();
  }

  on_file_load(file) {
    var self = this;
    // 1. 上传列表数量的限制
    //    只显示最近上传的一个，旧的会被新的顶掉
    var zippedBlob = file;
    var jsonfn = 'tables.json';
    zutil.unzipBlob(jsonfn, zippedBlob, function (unzippedBlob) {
      if (unzippedBlob !== undefined) {
        var reader = new FileReader();
        reader.onload = function (e) {
          //  console.log(JSON.parse(e.target.result));
          self.setState({tables: JSON.parse(e.target.result)});
        };
        reader.readAsText(unzippedBlob);
      }
    });
    return false;
  }

  render_rect(x, y, width, height, unitWidth) {
    return (
      <g fill="black">
        <rect x={(x + 1) * unitWidth} y={y * unitWidth}
              width={(width - 1) * unitWidth} height={1 * unitWidth}
              style={{fillOpacity: 0.5}}></rect>
        <rect x={(x + width) * unitWidth} y={y * unitWidth}
              width={1 * unitWidth} height={height * unitWidth}
              style={{fillOpacity: 0.5}}></rect>
        <rect x={(x + 1) * unitWidth} y={(y + height - 1) * unitWidth}
              width={(width - 1) * unitWidth} height={1 * unitWidth}
              style={{fillOpacity: 0.5}}></rect>
        <rect x={x * unitWidth} y={y * unitWidth}
              width={1 * unitWidth} height={height * unitWidth}
              style={{fillOpacity: 0.5}}></rect>
      </g>
    )
  }

  render_line(x, y, direction, length, unitWidth) {

    var width = 0,
      height = 0;
    if (direction === 'w') {
      width = 1;
      height = length;
    } else if (direction === 'n') {
      width = length;
      height = 1;
    } else if (direction === 'e') {
      width = 1;
      height = length;
    } else if (direction === 's') {
      width = length;
      height = 1;
    }

    return (
      <g fill="black">
        <rect x={x * unitWidth} y={y * unitWidth}
              width={width * unitWidth} height={height * unitWidth}
              style={{fillOpacity: 0.5}}></rect>
      </g>
    )
  }

  render_room(x, y, width, height, unitWidth, text) {
    return (
      <g fill="none">
        <rect x={x * unitWidth} y={y * unitWidth}
              width={width * unitWidth} height={height * unitWidth}
              style={{fillOpacity: 0.5, stroke: 'black', strokeWidth: 1}}></rect>
        <text x={(x + 1) * unitWidth} y={(y + 1) * unitWidth}>{text}</text>
      </g>
    )
  }


  render_tbl(id, x, y, direction, unitWidth, text, assigned, mhighlight) {
    // direction = { w东, n北, e西, s南}
    var width = 0,
      height = 0;
    if (direction === 'w') {
      width = 1;
      height = 3;
    } else if (direction === 'n') {
      width = 3;
      height = 1;
    } else if (direction === 'e') {
      width = 1;
      height = 3;
    } else if (direction === 's') {
      width = 3;
      height = 1;
    }

    var x_fill = (assigned && assigned !== '') ? 'aliceblue' : 'blue';
    const {selected} = this.state;
    if(mhighlight==1){
      x_fill = 'yellow';
    }
    if (selected === id) {
      x_fill = 'green';
    }

    return (
      <g fill={x_fill} className="mtable" key={id}>
        <rect x={x * unitWidth} y={y * unitWidth}
              width={width * unitWidth} height={height * unitWidth}
              style={{stroke: 'black', strokeWidth: 0.1}}
              onClick={this.on_selected_tbl_handler(id)}
        >{assigned}</rect>
        <text x={(x + 1) * unitWidth} y={(y + 1) * unitWidth}>{text}</text>
      </g>
    )
  }

  render() {
    const { props } = this;
    const { tables, tools, selected } = this.state;
    var height = 61,
      width = 101.3,
      highlight = 0,
      unitWidth = tools.zoom.value;



    // TODO 缓存这里,因为 大量的格子会造成性能问题
    var units = [];
    if (tools.grid.value) {
      for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
          units.push(
            <rect key={i + ',' + j}
                  x={i * unitWidth} y={j * unitWidth}
                  width={unitWidth} height={unitWidth}
                  style={{stroke: '#a9a9a9', strokeWidth: 0.1}}></rect>
          )
        }
      }
    }

    var lw = 6, rw = 18;
    var update_fields = undefined;
    if (selected !== undefined) {
      var selected_input = [];
      var selected_item = tables[selected];
      selected_input.push(
        <Row key={'x-ctrl-upd'}>
          <Col lg={lw}>
            x:
          </Col>
          <Col lg={rw}>
            <InputNumber value={selected_item.x}
                         onChange={this.on_change_handler('tables[' + selected + '].x')}/>
          </Col>
        </Row>
      );

      selected_input.push(
        <Row key={'y-ctrl-upd'}>
          <Col lg={lw}>
            y:
          </Col>
          <Col lg={rw}>
            <InputNumber value={selected_item.y}
                         onChange={this.on_change_handler('tables[' + selected + '].y')}/>
          </Col>
        </Row>
      );

      selected_input.push(
        <Row key={'direction-ctrl-upd'}>
          <Col lg={lw}>
            <div className="prop-key">direction:</div>
          </Col>
          <Col lg={rw}>
            <RadioGroup onChange={this.on_change_handler('tables[' + selected + '].direction')}
                        value={selected_item.direction}>
              <Radio key="a" value="w">东西</Radio>
              <Radio key="b" value="n">南北</Radio>
            </RadioGroup>
          </Col>
        </Row>
      );

      selected_input.push(
        <Row key={'assigned-ctrl-upd'}>
          <Col lg={lw}>
            <div className="prop-key">assigned:</div>
          </Col>
          <Col lg={rw}>
            <Input type="text" value={selected_item.assigned}
                   onChange={this.on_change_handler('tables[' + selected + '].assigned')}/>
          </Col>
        </Row>
      );

      update_fields = (
        <fieldset>
          <legend>Table properites</legend>
          {selected_input}
          <Button onClick={this.on_unselect}>Close</Button>
          <Button onClick={this.on_dodelete}>Delete</Button>
        </fieldset>
      );
    }

    var tool_inputs = [];
    tool_inputs.push(
      <label key={'-ctrl-zoom'} style={{marginLeft:'10px'}}>{tools.zoom.label}:
        <Slider value={tools.zoom.value}
                min={5} max={100} step={5}
                onChange={this.on_change_handler('tools.zoom.value')}/>
      </label>
    );

    tool_inputs.push(
      <label key={'-ctrl-grid'} style={{marginLeft:'10px'}}>{tools.grid.label}:
        <Switch checked={tools.grid.value} style={{marginLeft:'10px'}}
                onChange={this.on_change_handler('tools.grid.value')}/>
      </label>
    );
    tool_inputs.push(<p key={'-np-grid'} style={{marginBottom:'10px'}}></p>)
    tool_inputs.push(<hr key={'-cr-grid'}/>)

    tool_inputs.push(
      <Button type="dashed" icon="plus-circle-o" onClick={this.on_click_add} key={'-ctrl-add'}/>
    );
    tool_inputs.push(
      <Button type="dashed" icon="save" onClick={this.on_click_save} key={'-ctrl-save'}/>
    );
    tool_inputs.push(
      <FileLoader {...props} key={'-ctrl-load'}
                             onLoad={this.on_file_load}
                             multiple={false}>
        <Button type="dashed" icon="folder-open"/>
      </FileLoader>
    );
    tool_inputs.push(<br key={'-cr-btn'}/>)

    var tool_fields = (
      <fieldset>
        <legend style={{fontWeight:'bold',fontSize:'1.2em',marginLeft:'10px',marginBottom:'15px'}}>Tools</legend>
        {tool_inputs}
      </fieldset>
    );

    var locValue = this.props.lctStr;/*about click hightlight parameter*/
    var tbl_eles = [];
    var sFind =  this.props.InpValue;/*about search value hightlight parameter*/
    var vResult = [];
    if(sFind==""){
      console.log("input value is null");
      /*if text are "" remove this codes*/
      for(var i=0;i<tables.length;i++){
        tables[i].text = '';
      }
    }
    if(sFind!=""){
      var nPos;
      for(var i=0;i<tables.length;i++) {
        var sTxt = tables[i].assigned || '';
        nPos = sTxt.indexOf(sFind);
        if (nPos >= 0) {
          vResult[vResult.length] = sTxt;
        }
      }
    }
    for (var i = 0; i < tables.length; i++) {
      for(var j=0;j<vResult.length;j++){
        var tbVl = tables[i].assigned;
        if(vResult[j]== tbVl){
          highlight = 1;
        }
      }
      if(locValue==tables[i].assigned && locValue!= ""){
          if(sFind==tables[i].assigned){
            highlight = 1;
          }
      }
      tbl_eles.push(
        this.render_tbl(i, tables[i].x, tables[i].y, tables[i].direction, unitWidth, tables[i].text, tables[i].assigned,highlight)
      );
      highlight = "";
    }

    return (
      <div>
        <Row>
          <Col lg={24} md={24} sm={24} xs={24}>
            {tool_fields}
          </Col>
        </Row>
        <Row>
          <Col lg={20} md={6} sm={24} xs={24}>
            <div style={{overflowY: 'auto',
                        overflowX: 'auto',
                        width: '100%',
                        height: '600px',
                        borderWidth: '2px',
                        borderColor: '#bbb',
                        borderStyle: 'solid',
                        float: 'left'
                      }}>
              <svg xmlns="http://www.w3.org/2000/svg"
                   width={width * unitWidth} height={height * unitWidth}
                   version="1.1">
                <g fill="none">
                  {units}
                </g>

                <g fill="none" onClick={this.on_unselect}>
                  <rect x={0} y={0}
                        width={width * unitWidth} height={height * unitWidth}
                        style={{fill: "blue", fillOpacity: 0}}></rect>
                  <g fill="#666" style={{marginRight:'-20px'}}>
                    <rect x={0 * unitWidth} y={0 * unitWidth}
                          width={width * unitWidth} height={2 * unitWidth}
                          style={{fillOpacity: 0.5}}></rect>
                    <text x={45 * unitWidth} y={1.5 * unitWidth} style={{fill:"#fff"}}>水水水水 大海 水水水水</text>
                  </g>
                  {/* lab map */}
                  {this.render_line(23, 4, 'w', 22, unitWidth)}
                  {this.render_line(24, 4, 'n', 53, unitWidth)}
                  {this.render_line(77, 4, 'w', 22, unitWidth)}
                  {this.render_line(24, 25, 'n', 53, unitWidth)}

                  {this.render_line(29, 22, 'n', 13, unitWidth)}
                  {this.render_line(28, 22, 'w', 3, unitWidth)}
                  {this.render_line(42, 22, 'w', 3, unitWidth)}
                  {this.render_line(45, 22, 'w', 3, unitWidth)}
                  {this.render_line(53, 22, 'w', 3, unitWidth)}
                  {this.render_line(57, 18, 'n', 9, unitWidth)}
                  {this.render_line(65, 19, 'w', 6, unitWidth)}

                  {this.render_room(29, 23, 3, 2, unitWidth, 'Room')}
                  {this.render_room(24, 6, 3, 7, unitWidth, 'Meeting Room3')}
                  {this.render_room(24, 13, 3, 7, unitWidth, 'Boardroom')}
                  {this.render_room(55.9, 8, 4, 9, unitWidth, 'Testing Room')}
                  {this.render_room(59.9, 8, 4, 9, unitWidth, 'Customer Room')}
                  {this.render_room(66, 18, 2, 3, unitWidth, 'Room')}
                  {this.render_room(27, 22, 1, 3, unitWidth, '打印机')}

                  {/* main land */}
                  {this.render_line(6, 28, 'w', 32, unitWidth)}
                  {this.render_line(7, 28, 'n', 74, unitWidth)}
                  {this.render_line(80, 29, 'w', 16, unitWidth)}
                  {this.render_line(81, 44, 'n', 18, unitWidth)}
                  {this.render_line(98, 45, 'w', 15, unitWidth)}
                  {this.render_line(7, 59, 'n', 91, unitWidth)}

                  {this.render_line(15, 29, 'w', 2, unitWidth)}
                  {this.render_line(7, 34, 'n', 5, unitWidth)}
                  {this.render_line(7, 39, 'n', 5, unitWidth)}

                  {this.render_line(40, 29, 'w', 9, unitWidth)}
                  {this.render_line(40, 42, 'w', 17, unitWidth)}
                  {this.render_line(61, 29, 'w', 3, unitWidth)}
                  {this.render_line(61, 35, 'w', 24, unitWidth)}
                  {this.render_line(77, 41, 'n', 3, unitWidth)}
                  {this.render_line(80, 45, 'w', 5, unitWidth)}

                  {this.render_room(7, 40, 5, 19, unitWidth, 'Boardroom')}
                  {this.render_room(41, 31, 8, 7, unitWidth, 'Boardroom 2')}
                  {this.render_room(54, 35, 7, 6, unitWidth, 'HR')}
                  {this.render_room(54, 41, 7, 6, unitWidth, '$')}
                  {this.render_room(62, 29, 7, 2, unitWidth, 'Room')}
                  {this.render_room(73, 33, 7, 4, unitWidth, 'Server Room')}
                  {this.render_room(79, 38, 1, 3, unitWidth, '打印机')}
                  {this.render_room(81, 45, 6, 5, unitWidth, 'Meeting 2')}
                  {this.render_room(87, 45, 5, 5, unitWidth, 'Meeting 1')}
                  {this.render_room(92, 45, 6, 5, unitWidth, 'Meeting 0')}

                  {this.render_line(22, 51, 'w', 3, unitWidth)}
                  {this.render_line(23, 51, 'w', 3, unitWidth)}
                  {this.render_line(24, 51, 'w', 3, unitWidth)}
                </g>
                {tbl_eles}
              </svg>
            </div>
          </Col>
          <Col lg={4} md={18} sm={24} xs={24}>
            <div style={{overflowY: 'auto',
                        overflowX: 'auto',
                        height: '600px',
                        borderWidth: '2px',
                        borderColor: '#666',
                        borderStyle: 'solid'}}>
              {update_fields}
            </div>
          </Col>
        </Row>
      </div>
    );
  }


}
